<?php
class UserController extends Zend_Controller_Action
{
	protected $_acl;
	protected $_userGroup;
	public function preDispatch()
	{
		$auth = Zend_Auth::getInstance();
		if($auth->getIdentity()) {
			$this->view->auth = "success";
			$userInfo = $auth->getStorage()->read();
			$this->view->userInfo = $userInfo;
		}
		$Configuration = new Configuration();
		$configurationData = $Configuration->getConfigurationInfo();
		$this->view->configuration = $configurationData;
		$this->view->current = "admin";
	}
	
	public function init()
	{
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		$groupBase = new GroupBase();
		if ($userInfo) {
			$userGroups = $groupBase->getUserGroup($userInfo->name);
		}
		$this->_userGroup = $userGroups[0]['name'] ? $userGroups[0]['name'] : "Users";
		$this->_acl = new Acl_PPMIS();
		$this->view->acl = $this->_acl;
		$this->view->userGroup = $this->_userGroup;
	}
	
	public function browseAction()
	{
		// checking if user has the permissions to perform this operation
		
		if($this->_acl->isAllowed($this->_userGroup, null, "admin")) {
			$userBase = new UserBase();
			$propertyEntry = new PropertyEntry();
			$propertyString = new PropertyString();
			$membershipBase = new MembershipBase();
			
			$usersData = array();
			$users = $userBase->getAdapter()->fetchAll($userBase->select());
			$i = 0;
			foreach ($users as $user) {
				$usersData[$i]['id'] = $user['id'];
				$usersData[$i]['name'] = $user['name'];
				$propertyEntryData = $propertyEntry->getAdapter()->fetchAll($propertyEntry->select()->where('entry_id=?',$user['id']));
				
				foreach ($propertyEntryData as $pEntryData) {
					$propertyStringData = $propertyString->getAdapter()->fetchRow($propertyString->select()->where('id = ?',$pEntryData['id']));
					
					if($pEntryData['property_key'] == "Email") {
						$usersData[$i]['email'] = $propertyStringData['propertyvalue']; 
					}
					
					if($pEntryData['property_key'] == "fullname") {
						$usersData[$i]['fullname'] = $propertyStringData['propertyvalue']; 
					}
				}
				
				$membershipBaseData = $membershipBase->getAdapter()->fetchAll($membershipBase->select()->where('user_name = ?',$user['name']));
				$j = 0;
				foreach ($membershipBaseData as $membership){
					$usersData[$i]['groups'][$j] = $membership['group_name'];
					$j++;
				}
				
				$i++;
			}
			//Zend_Debug::dump($usersData);
			$this->view->usersData = $usersData;
		} else {
			$this->_redirect("user/invalid");
		}
	}
	
	public function viewAction()
	{
		if($this->_acl->isAllowed($this->_userGroup, null, "admin")) {
			$id = $this->_getParam('id');
			$userBase = new UserBase();
			$membershipBase = new MembershipBase();
			
			$usersData = $userBase->getUserById($id);
			$userData = array();
			$i = 0;
			foreach ($usersData as $user) {
				$userDatap['id'] = $user['uid'];
				$userData['name'] = $user['name'];
				if($user['property_key'] == "Email") {
					$userData['email'] = $user['propertyvalue']; 
				}
				
				if($user['property_key'] == "fullname") {
					$userData['fullname'] = $user['propertyvalue']; 
				}
				
			}
			$userData['groups'] = $membershipBase->getAdapter()->fetchAll($membershipBase->select()
													->from("membershipbase","group_name")
													->where('user_name = ?',$userData['name']));
			//Zend_Debug::dump($userData);
			$this->view->userData = $userData;
			//exit;
			} else {
				$this->_redirect("user/invalid");
			}
	}
	
	public function addAction()
	{
		if($this->_acl->isAllowed($this->_userGroup, null, "admin")) {	
			$userBase = new UserBase();
			$propertyString = new PropertyString();
			$propertyEntry = new PropertyEntry();
			$membershipBase = new MembershipBase();
			$form = new AddUserForm();
			
			if ($this->getRequest()->isPost()) {
				$formData = $this->_request->getPost();
				if ($form->isValid($formData)) {
					// inserting data in userbase table....
					$userBaseData = array(
						'name' => $formData['username'],
						'password' => md5($formData['password'])
					);
					$userBase->insert($userBaseData);
					$userId = $userBase->getAdapter()->lastInsertId();
					// inserting data in property string and property entry..
					
					$propertyEntryData = array(
						'entry_name' => 'OSUser',
						'entry_id' => $userId,
						'property_key' => 'Email',
						'propertytype' => 5
					);
					$propertyEntry->insert($propertyEntryData);
					$lastInsertId = $propertyEntry->getAdapter()->lastInsertId();
					
					$propertyStringData = array(
						'id' => $lastInsertId,
						'propertyvalue' => $formData['email']
					);
					
					$propertyString->insert($propertyStringData);
					
					$propertyEntryData = array(
						'entry_name' => 'OSUser',
						'entry_id' => $userId,
						'property_key' => 'fullname',
						'propertytype' => 5
					);
					$propertyEntry->insert($propertyEntryData);
					$lastInsertId = $propertyEntry->getAdapter()->lastInsertId();
					
					$propertyStringData = array(
						'id' => $lastInsertId,
						'propertyvalue' => $formData['fullName']
					);
					
					$propertyString->insert($propertyStringData);
					
					$membershipBaseData = array(
						'user_name' => $formData['username'],
						'group_name' => 'ppmis-users'
					);
					
					$membershipBase->insert($membershipBaseData);
				}
			}
			
			$this->view->form = $form;
		} else {
			$this->_redirect("user/invalid");
		}
	}
	
	public function editAction()
	{
		if($this->_acl->isAllowed($this->_userGroup, null, "admin")) {
			$id = $this->_getParam('id');
			$userBase = new UserBase();
			$propertyEntry = new PropertyEntry();
			$propertyString = new PropertyString();
			
			$usersData = $userBase->getUserById($id);
			$userData = array();
			$userData['id'] = $id;
			foreach ($usersData as $data) {
				if($data['property_key'] == 'fullname') {
					$userData['fullname'] = $data['propertyvalue'];
				}
				if($data['property_key'] == 'Email') {
					$userData['email'] = $data['propertyvalue'];
				}
			}
			$form = new EditUserForm();
			$form->populate($userData);
			if ($this->getRequest()->isPost()) {
				$formData = $this->_request->getPost();
				if ($form->isValid($formData)) {
					$pEntryData = $propertyEntry->getAdapter()->fetchAll($propertyEntry->select()->where('entry_id=?',$formData['id']));
					foreach ($pEntryData as $entry) {
						if ($entry['property_key'] == "fullname") {
							$fullnameId = $entry['id'];
						}
						if ($entry['property_key'] == "Email") {
							$emailId = $entry['id'];
						}
					}
					$propertyString->update(array('propertyvalue'=>$formData['fullname']),"id = $fullnameId");
					$propertyString->update(array('propertyvalue'=>$formData['email']),"id = $emailId");
					$this->_redirect('user/browse');		
				}
			}
			$this->view->fullname = $userData['fullname'];
			$this->view->form = $form;
		} else {
			$this->_redirect("user/invalid");
		}
	}
	
	public function changegroupsAction()
	{
		if($this->_acl->isAllowed($this->_userGroup, null, "admin")) {
			$id = $this->_getParam('id');
			$userBase = new UserBase();
			$groupBase = new GroupBase();
			$membershipBase = new MembershipBase();
			
			$allGroups = $groupBase->getAllGroups();
			
			if ($_POST) {
				$userName = $userBase->getAdapter()->fetchOne($userBase->select()->from('userbase','name')->where("id = ?",$_POST['id']));
				if ($_POST['leave']) {
					foreach ($_POST['groupsToLeave'] as $key=>$value) {
						$membershipBase->delete("user_name = '$userName' AND group_name = '$value'");
					}
				}
				if ($_POST['join']) {
					foreach ($_POST['groupsToJoin'] as $key=>$value) {
						$membershipBase->insert(array(
									'user_name' => $userName,
									'group_name' => $value
								));
					}
				}
			}
			
			$userGroups = $membershipBase->getUserGroups($id);
			$userGroupsNames = array();
			$i = 0;
			foreach ($userGroups as $uGroup) {
				$userGroupsNames[$i] = $uGroup['group_name'];
				$i++;
			}
			
			$allGroups = $groupBase->getAllGroups();
			
			$availableGroups = array();
			$i = 0;
			foreach ($allGroups as $group) {
				if(!in_array($group['groupname'],$userGroupsNames)) {
					$availableGroups[$i]['groupname'] = $group['groupname'];
				}
			$i++;
			}
			
			$this->view->id = $id;
			$this->view->userGroups = $userGroups;
			$this->view->availableGroups = $availableGroups;
		} else {
			$this->_redirect("user/invalid");
		}
	}
	
	public function openissues()
	{
		$this->view->current = "project";
		$pid = $this->_getParam('pid');
		$project = new Project();
		$projectData = $project->getAdapter()->fetchRow($project->select()->where('id=?',$pid));
	}
	
	public function invalidAction()
	{
		
	}
}